package com.eventosgasteiz.server;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eventosgasteiz.server.bbdd.Imagen;
import com.eventosgasteiz.server.bbdd.PMF;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class ServeImageServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8240948336626186283L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		_doExec(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		_doExec(req, resp);
	}

	private void _doExec(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		try {
			String idStr = req.getParameter("id");
			String idWithoutExt = idStr.substring(0,idStr.indexOf("."));
			long id = new Long(idWithoutExt).longValue();
			imageFor(id, resp);
		} catch (Exception e) {
			return;
		}
	}
	
	void imageFor(long id, HttpServletResponse res) throws IOException {
	    // find desired image
		try {
		    PersistenceManager pm = PMF.get().getPersistenceManager();
		    Key k = KeyFactory.createKey(Imagen.class.getSimpleName(), id);
	        Imagen i = pm.getObjectById(Imagen.class, k);
		    Blob image = i.getImage();
	
		    // serve the first image
		    res.setContentType("image/jpeg");
		    res.getOutputStream().write(image.getBytes());
		} catch (Exception e) {
			return;
		}
	}
	
}
